/**
 * Created by zhouli on 18/2/7
 * Email li.zhou@huilianyi.com
 */
import React from 'react';
import {connect} from 'react-redux';
import BankCard from 'containers/enterprise-manage/person-manage/person-detail/person-detail-components/bank-card';
import SomeIdCard from 'containers/enterprise-manage/person-manage/person-detail/person-detail-components/some-id-card';
import BasicInfo from 'containers/enterprise-manage/person-manage/person-detail/person-detail-components/basic-info';
import VendorInfo from 'containers/enterprise-manage/person-manage/person-detail/person-detail-components/vendor-info';
import moment from 'moment';
import {messages, deepCopy} from 'share/common';
import 'styles/enterprise-manage/person-manage/person-detail/person-detail.scss';
import PDService from 'containers/enterprise-manage/person-manage/person-detail/person-detail.service';
import menuRoute from 'routes/menuRoute';
import {Button, Icon, message, Modal, DatePicker} from 'antd';
import {
  personObjDefault,
  bankAccountDefault,
  contactCardDefault,
  vendorInfoDefault,
  vendorInfoDefaultWithPerson
} from 'containers/enterprise-manage/person-manage/person-detail/person-detail.model';

class PersonDetail extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      leaveDateLoading: false,
      isReadOnly: this.props.currentPageRoute.operationType ==='R' || false,
      loading: true,
      showSelectTime: false,//选择离职时间的模态框
      hireTime: null,//离职时间
      data: [],
      BasicInfoEditing: false,//基本信息：是否编辑
      VendorEditing: false,//供应商信息：是否编辑
      personObj: {},//人员信息对象，包含基本信息与扩展字段信息
      bankCards: [],//银行卡
      contactCards: [],//证件信息
      hasCtripVendor: false, //是否有携程
      vendorInfo: vendorInfoDefault,//供应商
      userCompanyProfile:{},
    }
  }

  componentDidMount() {
    this.initPage(this.props.params.userOID)
  }

  initPage(oid) {
    if (oid === "NEW") {
      // 此函数1009上线的时候放开
      this.getInitExtendField();
      // this.setState({
      //   personObj: deepCopy(personObjDefault),
      //   // bankCards: bankAccountDefault,
      //   // contactCards: contactCardDefault,
      //   // vendorInfo: vendorInfoDefault,
      //   BasicInfoEditing: true,
      // });
    } else {
      bankAccountDefault.userOID = this.props.params.userOID;
      contactCardDefault.userOID = this.props.params.userOID;
      this.getPersonDetail();
      this.getBankCards();
      this.getContactCards();
      this.setCtripVendor();
    }
    //人员导入方式：this.props.company.createDataType如果是 1002，属于接口导入
    // 新增与导入按钮需要隐藏
  }

  //获取初始化自定义表单字段
  getInitExtendField = () => {
    let params = {
      formOID: this.props.profile["_self.company.contact.custom.form"]
    }
    PDService.getInitExtendField(params)
      .then((res) => {
        let data = res.data;
        let personObj = deepCopy(personObjDefault);
        personObj.customFormValues = data;
        this.setState({
          personObj,
          BasicInfoEditing: true,
        }, () => {
          if (this.state.personObj.customFormValues && this.state.personObj.customFormValues.length > 0) {
            this.getPersonDetailEnumerationList();
          }
        });
      })
  }

  //是否有供应商信息
  setCtripVendor = () => {
    this.setState({
      hasCtripVendor: true//统一全部都显示，不受fp控制了
    }, () => {
      this.getSupplierInfo();
    })
  }

  //获取人员信息
  getPersonDetail = (userOID) => {
    let _userOID = this.props.params.userOID;
    if (userOID) {
      _userOID = userOID;
    }
    //编辑更新
    PDService.getPersonDetail(_userOID)
      .then((res) => {
        let data = res.data;
        if (data.gender === 0) {
          data.genderName = messages('enterprise-manage.key279'/*男*/);
        } else if (data.gender === 1) {
          data.genderName = messages('enterprise-manage.key244'/*女*/);
        } else {
          data.genderName = messages('enterprise-manage.key280'/*未知*/);
        }
        if (data.countryCode === undefined) {
          data.mobileCode = "86";
          data.countryCode = "CN";
        }
        //公司随着用户岗位改变会改变
        //如果是老公司，不要从这里拿companyOID，否则会拿到法人实体oid,
        //需要从 /api/my/companies 里面拿
        if(this.props.isOldCompany){
          PDService.getUserCompanyProfile(this.props.company.companyOID)
            .then(res=>{
              this.setState({
                userCompanyProfile: res.data.profileDetail,
                personObj: data
              }, () => {
                if (this.state.personObj.customFormValues && this.state.personObj.customFormValues.length > 0) {
                  this.getPersonDetailEnumerationList();
                }
              });
            })
        }else {
          PDService.getUserCompanyProfile(data.companyOID)
            .then(res=>{
              this.setState({
                userCompanyProfile: res.data.profileDetail,
                personObj: data
              }, () => {
                if (this.state.personObj.customFormValues && this.state.personObj.customFormValues.length > 0) {
                  this.getPersonDetailEnumerationList();
                }
              });
            })
        }
      })
  };
  //获取扩展字段中的值列表
  getPersonDetailEnumerationList = () => {
    let personObj = this.state.personObj;
    let customFormValues = personObj.customFormValues;
    for (let i = 0; i < customFormValues.length; i++) {
      if (customFormValues[i].messageKey === "cust_list") {
        let dataSource = null;
        try {
          dataSource = JSON.parse(customFormValues[i].dataSource);
        } catch (e) {
        }
        if (dataSource && dataSource.customEnumerationOID) {
          PDService.getListByCustomEnumerationOID(dataSource.customEnumerationOID)
            .then((res) => {
              this.setPersonDetailEnumerationList(res.data, customFormValues[i])
            })
        }
      }
    }
  }

  //设置扩展字段中的值列表
  //把值列表挂在对应字段上
  setPersonDetailEnumerationList = (customEnumerationList, filed) => {
    let personObj = deepCopy(this.state.personObj);
    let customFormValues = personObj.customFormValues;
    for (let i = 0; i < customFormValues.length; i++) {
      if (customFormValues[i].fieldOID === filed.fieldOID) {
        customFormValues[i].customEnumerationList = customEnumerationList;
        //每设置一次，都需要更新一下
        //后端可能返回的是值列表值对应的code（value），不是messageKey，需要找一下
        //参见bug13014
        this.setState({
          personObj: personObj
        })
      }
    }
  }

  //获取银行信息
  getBankCards = () => {
    //编辑更新
    PDService.getBankCards(this.props.params.userOID)
      .then((res) => {
        this.setState({
          bankCards: res.data
        });
      })
  };


  //获取证件信息
  getContactCards = () => {
    //编辑更新
    PDService.getContactCards(this.props.params.userOID)
      .then((res) => {
        this.setState({
          contactCards: res.data
        });
      })
  };

  //获取供应商信息
  getSupplierInfo = () => {
    PDService.getSupplierInfo(this.props.params.userOID)
      .then((res) => {
        //需要用deepCopy，不然有对象引用导致的缓存
        let _vendorInfo = deepCopy(vendorInfoDefaultWithPerson);
        _vendorInfo.userOID = this.props.params.userOID;
        let vendorInfo = null;
        //如果有供应商信息
        if (!!res.data) {
          vendorInfo = Object.assign(_vendorInfo, res.data)
        } else {
          vendorInfo = _vendorInfo;
        }
        //代订名单 只显示第一个
        if(vendorInfo.agencyBookList &&
          vendorInfo.agencyBookList.length &&
          vendorInfo.agencyBookList.length > 0){
          vendorInfo._agencyBookList = vendorInfo.agencyBookList[0].fullName;
          vendorInfo._agencyBookListPopover = vendorInfo.agencyBookList.map(item => item.fullName).join(',');
          if(vendorInfo.agencyBookList.length > 1){
            vendorInfo._agencyBookList = vendorInfo._agencyBookList + "..."
          }
        }
        this.setState({
          vendorInfo: vendorInfo
        });
      })
  }

  //保存基本信息
  savedBasicInfoData = (person) => {
    this.props.params.userOID = person.userOID;
    //更新了人员信息，重新初始化页面
    this.initPage(person.userOID);
    this.BasicInfoToNoEditing();
  }
  //个人基本信息:编辑
  BasicInfoToEditing = () => {
    if(this.state.isReadOnly)return
    this.setState({
      BasicInfoEditing: true,
    });
  };
  //个人基本信息
  BasicInfoToNoEditing = () => {
    this.setState({
      BasicInfoEditing: false,
    });
  };

  //创建银行卡后
  //或者编辑银行卡后
  createCardOver = () => {
    this.getBankCards();
  }
  //创建证件后
  createContactCardOver = () => {
    this.getContactCards();
  }


  //保存供应商信息
  savedVendorExtendData = (obj) => {
    this.getSupplierInfo();
    this.VendorToNoEditing();
  }
  //个人供应商信息:编辑
  VendorToEditing = () => {
    this.setState({
      VendorEditing: true,
    });
  };
  //个人供应商信息
  VendorToNoEditing = () => {
    this.setState({
      VendorEditing: false,
    });
  };

  //离职该员工
  setResignDate = () => {
    let date = this.state.hireTime;
    if (date) {
      this.setState({
        leaveDateLoading: true,
      })
      date = moment(date).format("YYYY-MM-DD");
      PDService.setResignDate(this.props.params.userOID, date)
        .then((res) => {
          message.success(messages('enterprise-manage.key281'/*操作成功*/));
          this.getPersonDetail();
          this.setState({
            leaveDateLoading: false,
            showSelectTime: false,
            hireTime: null,
          })
        }).catch(err => {
        this.setState({
          leaveDateLoading: false,
        })
      })
    } else {
      message.success(messages('enterprise-manage.key282'/*请选择离职时间*/));
    }

  };
  //撤销离职
  cancelResign = () => {
    PDService.cancelResign(this.props.params.userOID)
      .then((res) => {
        message.success(messages('enterprise-manage.key281'/*操作成功*/));
        this.getPersonDetail();
      })
  };
  //重新入职
  rehire = () => {
    PDService.rehire(this.props.params.userOID)
      .then((res) => {
        message.success(messages('enterprise-manage.key281'/*操作成功*/));
        this.getPersonDetail();
      })
  };
  setResignDateModel = () => {
    this.setState({
      showSelectTime: true,
      hireTime: null,
    })
  }
  hideSelectTime = () => {
    this.setState({
      hireTime: null,
      showSelectTime: false
    })
  }
  handleChangeHireTime = (time) => {
    this.setState({
      hireTime: time,
    })
  }
  //根据员工状态渲染顶部按钮
  //   status: 1001,//不传代表只查询在职，1001也是在职，1002待离职员工，1003离职员工
  renderTopBtnByStatus = (user) => {
    const {isReadOnly}=this.state
    if (user.userOID) {
      if (user.status === 1002) {
        return (<div>
          <Button disabled={isReadOnly} onClick={this.setResignDateModel}>
            {messages('enterprise-manage.key283'/*修改离职时间*/)}
          </Button>
          &nbsp;&nbsp;&nbsp;
          <Button disabled={isReadOnly} onClick={this.cancelResign}>
            {messages('enterprise-manage.key284'/*撤销离职*/)}
          </Button>
        </div>)
      } else if (user.status === 1003) {
        return (<div>
          <Button disabled={isReadOnly} onClick={this.rehire}>
            {messages('enterprise-manage.key285'/*重新入职*/)}
          </Button>
        </div>)
      } else if (user.status === 1001) {
        return (<div>
          <Button disabled={isReadOnly} onClick={this.setResignDateModel}>
            {messages('enterprise-manage.key286'/*离职该员工*/)}
          </Button>
        </div>)
      } else {
        return (<div/>)
      }
    } else {
      return (<div/>)
    }
  }

  //基本信息
  renderEditBtn = (val) => {
    console.log('renderEditBtn', this.props.company.createDataType);
    let {isReadOnly}= this.state
    if (!val &&
      this.state.personObj.status !== 1003 &&
      (parseInt(this.props.company.createDataType) !== 1002)) {
      return (
        <div className={`f-left person-detail-edit-icon ${isReadOnly? 'disabled':''}`}
             onClick={!isReadOnly && this.BasicInfoToEditing}>
          <Icon type="edit"/>
          <span className="edit-text">
            {messages("common.edit")}
          </span>
        </div>
      )
    } else {
      return (<div/>)
    }
  }

  //渲染银行卡信息，必须与租户管理员权限且不是接口导入模式，才能编辑
  renderBankCards = (cards) => {
    const isReadOnly= this.state.isReadOnly
    if (cards.length > 0) {
      let dom = [];
      cards.map((data, index) => {
        dom.push(<div className="f-left bank-card-item">
          <BankCard
            isShowEditBtn={this.state.personObj.status !== 1003 &&
            (parseInt(this.props.company.createDataType) !== 1002) &&
            !isReadOnly}
            createCardOver={this.createCardOver}
            cardInfo={data}
            key={"is-empty-bank-card" + data.contactBankAccountOID}/>
        </div>)
      })
      //加一个空银行卡：有限制条件的
      if (this.state.personObj.status !== 1003 &&
        (parseInt(this.props.company.createDataType) !== 1002)) {
        dom.push(
          <div className="f-left bank-card-item">
            <BankCard isEmpty={true}
                      isReadOnly={isReadOnly}
                      createCardOver={this.createCardOver}
                      cardInfo={bankAccountDefault}
                      key={"is-empty-bank-card"}/>
          </div>
        )
      }
      return (
        <div className="bank-card-list">
          {dom}
          <div className="clear"/>
        </div>
      )
    } else {
      if (this.state.personObj.status !== 1003 &&
        (parseInt(this.props.company.createDataType) !== 1002)) {
        return (
          <div className="bank-card-list">
            <div className="f-left bank-card-item">
              <BankCard isEmpty={true}
                        isReadOnly={isReadOnly}
                        createCardOver={this.createCardOver}
                        cardInfo={bankAccountDefault}
                        key={"is-empty-bank-card"}/>
            </div>
            <div className="clear"/>
          </div>
        )
      } else {
        return <span/>
      }
    }
  }

  //渲染证件信息，必须与租户管理员权限且不是接口导入模式，才能编辑
  renderContactCards = (cards) => {
    const isReadOnly= this.state.isReadOnly
    if (cards.length > 0) {
      let dom = [];
      cards.map((data, index) => {
        dom.push(<div className="f-left id-card-item">
          <SomeIdCard
            isShowEditBtn={this.state.personObj.status !== 1003 &&
            (parseInt(this.props.company.createDataType) !== 1002) &&
            !isReadOnly}
            createCardOver={this.createContactCardOver}
            cardInfo={data}
            key={"is-empty-id-card" + data.contactCardOID}/>
        </div>)
      })
      //加一个空证件：有限制条件的
      if (this.state.personObj.status !== 1003 &&
        (parseInt(this.props.company.createDataType) !== 1002)) {
        dom.push(
          <div className="f-left bank-card-item">
            <SomeIdCard isEmpty={true}
                        isReadOnly={isReadOnly}
                        createCardOver={this.createContactCardOver}
                        cardInfo={contactCardDefault}
                        key={"is-empty-id-card"}/>
          </div>
        )
      }

      return (
        <div className="bank-card-list">
          {dom}
          <div className="clear"/>
        </div>
      )
    } else {
      if (this.state.personObj.status !== 1003 &&
        (parseInt(this.props.company.createDataType) !== 1002)) {
        return (
          <div className="bank-card-list">
            <div className="f-left id-card-item">
              <SomeIdCard isEmpty={true}
                          isReadOnly={isReadOnly}
                          createCardOver={this.createContactCardOver}
                          cardInfo={contactCardDefault}
                          key={"is-empty-id-card"}/>
            </div>
            <div className="clear"/>
          </div>
        )
      } else {
        return <span/>
      }
    }
  }

  //供应商
  renderVendorEditBtn = (val) => {
    const {isReadOnly}=this.state
    if (!val && this.state.personObj.status !== 1003 &&
      (parseInt(this.props.company.createDataType) !== 1002)) {
      return (
        <div className={`f-left person-detail-edit-icon ${isReadOnly? 'disabled': ''}`}
             onClick={!isReadOnly && this.VendorToEditing}>
          <Icon type="edit"/>
          <span className="edit-text">
            {messages("common.edit")}
          </span>
        </div>
      )
    } else {
      return (<div/>)
    }
  }

  //是否渲染 携程供应商
  renderCtripVendor = (val, userCompanyProfile) => {
    const {isReadOnly}=this.state
    let filed = PDService.getRenderList(userCompanyProfile);
    if (val && filed.length) {
      return (
        <div className="vendor-info-wrap">
          <div className="card-wrap-title">
            <div className="f-left">
              {messages('enterprise-manage.key390')/*消费商信息*/}
            </div>
            {this.renderVendorEditBtn(this.state.VendorEditing)}
            <div className="clear"/>
          </div>
          <VendorInfo
            userCompanyProfile={userCompanyProfile}
            savedData={this.savedVendorExtendData}
            toEditing={this.VendorToEditing}
            toNoEditing={this.VendorToNoEditing}
            vendorObj={this.state.vendorInfo}
            originEditingStatus={this.state.VendorEditing}
          />
        </div>
      )
    } else {
      return (<div/>)
    }
  }

  handleBack = () => {
    this.context.router.push(menuRoute.getRouteItem('person-manage').url);
  };

  renderInfoByUseIsNew = (user) => {
    let {bankCards, hasCtripVendor, contactCards, userCompanyProfile} = this.state;
    if (user.userOID) {
      return (
        <div>
          <div className="pd-card-wrap">
            <div className="card-wrap-title">
              {messages('enterprise-manage.key288'/*银行卡信息*/)}
            </div>
            {this.renderBankCards(bankCards)}
          </div>
          <div className="pd-id-card-wrap">
            <div className="card-wrap-title">
              {messages('enterprise-manage.key289'/*证件信息*/)}
            </div>
            {this.renderContactCards(contactCards)}
          </div>
          {/*根据配置，是否渲染携程供应商*/}
          {this.renderCtripVendor(hasCtripVendor, userCompanyProfile)}
        </div>
      )
    } else {
      return ""
    }
  }

  render() {
    return (
      <div className="person-detail-wrap">
        <div className="person-detail-top-wrap">
          {this.renderTopBtnByStatus(this.state.personObj)}
        </div>
        <div className="basic-info-wrap">
          <div className="basic-info-title">
            <div className="f-left">
              {messages('enterprise-manage.key290'/*个人基本信息*/)}
            </div>
            {this.renderEditBtn(this.state.BasicInfoEditing)}
            <div className="clear"/>
          </div>
          {/*这个地方直接写组件，不依赖于state渲染，导致组件componentWillMount钩子没有执行*/}
          <BasicInfo
            savedData={this.savedBasicInfoData}
            toEditing={this.BasicInfoToEditing}
            toNoEditing={this.BasicInfoToNoEditing}
            basicInfoData={this.state.personObj}
            originEditingStatus={this.state.BasicInfoEditing}/>
        </div>
        {this.renderInfoByUseIsNew(this.state.personObj)}
        <a style={{fontSize: '14px', paddingBottom: '20px'}} onClick={this.handleBack}>
          <Icon type="rollback" style={{marginRight: '5px'}}/>
          {messages('common.back')}
        </a>

        <div className="person-detail-wrap-for-model"/>
        <Modal
          getContainer={() => {
            return document.getElementsByClassName("person-detail-wrap-for-model")[0];
          }}
          closable
          width={600}
          className="show-select-hire-time-modal"
          title={messages('enterprise-manage.key291'/*设置离职时间*/)}
          visible={this.state.showSelectTime}
          footer={null}
          onCancel={this.hideSelectTime}
          destroyOnClose={true}
        >
          <div className="hire-time-content">
            <DatePicker
              className="hire-time-content-date"
              format={'YYYY-MM-DD'}
              value={this.state.hireTime}
              defaultValue={this.state.hireTime}
              onChange={this.handleChangeHireTime}/>
            <div style={{marginTop: 10}}>{messages('enterprise-manage.key405')/*离职员工前，请务必确认该员工已办理好所有单据。员工被离职后，将不能继续登录汇联易系统。*/}</div>
          </div>
          <div className="hire-time-footer">
            <Button className="hire-time-cancel" onClick={this.hideSelectTime}>
              {messages("common.cancel")}
            </Button>
            <Button type="primary"
                    loading={this.state.leaveDateLoading}
                    onClick={this.setResignDate}>
              {messages("common.ok")}
            </Button>
          </div>
        </Modal>
      </div>
    )
  }
}

PersonDetail.contextTypes = {
  router: React.PropTypes.object
};
PersonDetail.propTypes = {};

function mapStateToProps(state) {
  return {
    isOldCompany: state.login.isOldCompany,
    profile: state.login.profile,
    user: state.login.user,
    company: state.login.company,
    currentPageRoute: state.main.currentPageRoute
  }
}

export default connect(mapStateToProps)(PersonDetail);
